﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Elsa.Common.Models;
using Elsa.Common.Multitenancy;
using Elsa.CSharp.Activities;
using Elsa.EntityFrameworkCore.Extensions;
using Elsa.EntityFrameworkCore.Modules.Management;
using Elsa.EntityFrameworkCore.Modules.Runtime;
using Elsa.Expressions.Contracts;
using Elsa.Expressions.Models;
using Elsa.Extensions;
using Elsa.JavaScript.Activities;
using Elsa.JavaScript.Models;
using Elsa.Labels.Endpoints.Labels.List;
using Elsa.Workflows;
using Elsa.Workflows.Activities;
using Elsa.Workflows.Activities.Flowchart.Activities;
using Elsa.Workflows.Builders;
using Elsa.Workflows.IncidentStrategies;
using Elsa.Workflows.Management;
using Elsa.Workflows.Management.Entities;
using Elsa.Workflows.Management.Filters;
using Elsa.Workflows.Management.Mappers;
using Elsa.Workflows.Management.Models;
using Elsa.Workflows.Memory;
using Elsa.Workflows.Models;
using Elsa.Workflows.Options;
using Elsa.Workflows.Runtime;
using Elsa.Workflows.Runtime.Messages;
using Elsa.Workflows.State;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
//using T.ServiceComponent.I18N.SPI;
using T.FAS.Runtime.MF.Activities;
using T.FAS.Runtime.MF.Activities.ActivityInputOutput;
using T.FAS.Runtime.MF.Activities.Helper;
using T.FAS.Runtime.MF.Activities.Nodes;
using T.FAS.Runtime.MF.Activities.Services;
using T.FAS.Runtime.MF.Dao.Dao;
using T.FAS.Runtime.MF.Entity;
using T.FAS.Runtime.MF.Runtime.Core;
using T.FAS.Runtime.MF.SPI;
using T.ServiceComponent.Database.Service;
using T.ServiceComponent.Kernel.Service;
using YamlDotNet.Serialization;
using ActivityExecutionRecord = T.FAS.Runtime.MF.Entity.ElsaEntity.ActivityExecutionRecord;

public class ElsaEngine : IElsaEngine, IDisposable
{
    private static readonly Lazy<Task<ElsaEngine>> _lazyInstance = new Lazy<Task<ElsaEngine>>(CreateEngineInstance);
    private readonly ServiceProvider _sp;
    private readonly IWorkflowRunner _runner;
    private readonly IWorkflowStarter _starter;
    private readonly IWorkflowDefinitionService _defSrv;
 
    // 私有构造函数
    private ElsaEngine(ServiceProvider sp)
    {
        _sp = sp;
        // 从容器中取出 Runner 与 Registry
        _starter = _sp.GetRequiredService<IWorkflowStarter>();
        _runner = _sp.GetRequiredService<IWorkflowRunner>();
        _defSrv = _sp.GetRequiredService<IWorkflowDefinitionService>();
    }

    /// <summary>
    /// 获取单例实例
    /// </summary>
    public static Task<ElsaEngine> GetInstanceAsync() => _lazyInstance.Value;

    /// <summary>
    /// 执行工作流
    /// </summary>
    public async Task<ElsaExecutionResult> ExecuteAsync(
        string definitionId,
        IDictionary<string, object> input,
        Dictionary<string,string> extraParams=null,
        CancellationToken cancellationToken = default)
    {
        // 1) 查最新版本定义
        var workflowDefinition = await GetWorkflowAsync(definitionId, cancellationToken);
        if (workflowDefinition is null)
            throw new InvalidOperationException($"Workflow '{definitionId}' not found.");
        // 从定义构建工作流
        var workflow = await _defSrv.MaterializeWorkflowAsync(workflowDefinition, cancellationToken);
        // 2) 构造 RunWorkflowOptions 输入参数
        var options = new RunWorkflowOptions
        {
            // Elsa 3.x 中，这里是一个 Variables 类型
            Input = input,

            // 以下都是可选，你可以按需设置：
            // WorkflowInstanceId   = null,   // 如果想恢复一个已存在的实例
            // StartingActivityId   = null,   // 手动指定从哪个 Activity 开始跑
            // CorrelationId        = "...",  // 关联系统中其它实体
            // PublishEvents        = true,   // 是否触发 Event 活动
            // PersistWorkflows     = true    // 是否持久化实例状态（对 Memory 存储可忽略）
        };
        if (extraParams!=null)
        {
            CallContext.SetData("WorkflowDebugParam", extraParams);
        }
        // 3) 执行流程
        //RunWorkflowResult result = await _runner.RunAsync(workflow, null, cancellationToken);
     var result =  _runner.RunAsync(workflow, options, cancellationToken).GetAwaiter().GetResult();

        var workflowState = result.WorkflowState;
        var excuteContext = result.WorkflowExecutionContext;
        // 4) 返回包装结果
        return new ElsaExecutionResult
        {
            Status = GetWorkflowStatus(result.WorkflowState),
            //Output = result.Result,
            Output = excuteContext.Output,
            Inputs= excuteContext.Input,
            //WorkflowState = result.WorkflowState,
            InstanceID = workflowState.Id,
            CreateAt = workflowState.CreatedAt.UtcTicks,
            FinishedAt = workflowState.FinishedAt.HasValue ? workflowState.FinishedAt.Value.UtcTicks : null,
            ElapsedTime = workflowState.FinishedAt.HasValue ? workflowState.FinishedAt.Value.Subtract(workflowState.CreatedAt).TotalSeconds : null,
            Exception = string.Join(",",workflowState.Incidents.Select(t => t.Exception.Message))
        };

        string GetWorkflowStatus(WorkflowState workflowState)
        {
            var status = string.Empty;
            //当workflow完成时，显示真实的完成状态，如：完成，取消，失败
            if (workflowState.Status== WorkflowStatus.Finished)
            {
                status= workflowState.SubStatus.ToString();
            }
           else //否则显示执行中
            {
                status= workflowState.Status.ToString();
            }

            if (status== "Pending")
            {
                status = "waiting";
            }
            else if (status == "Executing")
            {
                status = "running";
            }
            else if (status == "Suspended")
            {
                status = "waiting";
            }
            else if (status == "Finished")
            {
                status = "succeeded";
            }
            else if (status == "Cancelled")
            {
                status = "stopped";
            }
            else if (status == "Faulted")
            {
                status = "failed";
            }
            return status;
        }
    }

    /// <summary>
    /// 直接发起新流程，不等待结果
    /// </summary>
    /// <param name="definitionId"></param>
    /// <param name="input"></param>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    /// <exception cref="InvalidOperationException"></exception>
    public async Task<RunWorkflowInstanceResponse> StartNewWorkflowInstanceAsync(
        string definitionId,
        IDictionary<string, object> input,
        CancellationToken cancellationToken = default)
    {
        var startReq = new StartWorkflowRequest
        {
            WorkflowDefinitionHandle = WorkflowDefinitionHandle.ByDefinitionId(definitionId, VersionOptions.Latest),
            Input = input,
        };

        StartWorkflowResponse result = await _starter.StartWorkflowAsync(startReq, cancellationToken);

        return result.ToRunWorkflowInstanceResponse();
    }
    /// <summary>
    /// 发布工作流--需要根据具体参数进行调整
    /// </summary>
    /// <param name="defJson"></param>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    public async Task<WorkflowDefinition> PublishAsync(Microflow def,
        CancellationToken cancellationToken = default)
    {
       // return await SaveCustomActivity();
       // return await SaveCDOActivity();
        
        var _mapper = _sp.GetRequiredService<WorkflowDefinitionMapper>();
        var _defPublisher = _sp.GetRequiredService<IWorkflowDefinitionPublisher>();
        var _builder = _sp.GetRequiredService<WorkflowBuilder>();
        _builder.WithDefinitionId(def.Id);
        _builder.Id = Guid.NewGuid().ToString();
        _builder.Description = def.ItemDescription;
        _builder.Name = def.ItemName;
        //_builder.Result = new Variable("Variable1");
        var activities = new List<IActivity>();
        var connections = new List<Elsa.Workflows.Activities.Flowchart.Models.Connection>();
        var variables = new List<Variable>();
        //获取所有节点的端口
        var ports =def.DesignData.Cells.Where(t=>t.Ports!=null).SelectMany(t => t.Ports.Items);
        //添加activity
        foreach (var cell in def.DesignData.Cells)
        {
            if (cell is INodeMapper mapper)
            {
                //父级为空，表示在某个子容器里面，不在这里添加，添加到子容器里面
                if (cell.Parent==null)
                {
                    activities.Add(mapper.MapToActivity());
                }
               

                //添加变量，不管是子容器里面的节点还是非子容器里面的节点，都添加的工作流中的变量中
                _builder.WithVariables(mapper.Variables.ToArray());
                //添加输出
                if (mapper.Outputs != null)
                {
                    _builder.Outputs.AddRange(mapper.Outputs.ToArray());
                }
                //添加输入
                if (mapper.Inputs != null)
                {
                    _builder.Inputs.AddRange(mapper.Inputs.ToArray());
                }
            }
            
        }
        //添加connection
        foreach (var cell in def.DesignData.Cells)
        {
            if (cell is Edge edge)
            {
                var sourceActivity = activities.Find(t => t.Id == edge.Source.Cell);
                var targetActivity = activities.Find(t => t.Id == edge.Target.Cell);
                if (sourceActivity == null || targetActivity == null) continue;

                connections.Add(new Elsa.Workflows.Activities.Flowchart.Models.Connection
                {
                    Source = new Elsa.Workflows.Activities.Flowchart.Models.Endpoint { Activity = sourceActivity, Port = ActivityHelper.GetActivityPort(sourceActivity, ports.FirstOrDefault(t => t.Id == edge.Source.Port)) },
                    Target = new Elsa.Workflows.Activities.Flowchart.Models.Endpoint { Activity = targetActivity, Port = ActivityHelper.GetActivityPort(targetActivity, ports.FirstOrDefault(t => t.Id == edge.Target.Port)) }
                });
            }
        };

        
        _builder.Root = new Flowchart
        {
            Activities = activities,
            Connections = connections,
        };
       // _builder.WorkflowOptions.IncidentStrategyType = typeof(ContinueWithIncidentsStrategy);
          var workflow3 = await _builder.BuildWorkflowAsync(cancellationToken);
      
        var workflowDef = _mapper.Map(workflow3);

        workflowDef.CreatedAt = DateTime.UtcNow;
        return await _defPublisher.SaveDraftAsync(_mapper.MapToWorkflowDefinition(workflowDef));
        
    }

    /// <summary>
    /// 获取工作执行详细信息
    /// </summary>
    /// <param name="defJson"></param>
    public List<WorkflowInstanceDetail> GetExecuteDetail(string instanceId)
    {
        var instanceDao = new WorkflowInstanceDao();
        var definitionDao = new WorkflowDefinitionDao();
        var activityRecordDao = new ActivityExecutionRecordDao();
        var executeLogRecordDao = new WorkflowExecutionLogRecordDao();

        var activitySerializer = _sp.GetRequiredService<IActivitySerializer>();

        //var bookMarkSerializer = _sp.GetRequiredService<IBookmarkPayloadSerializer>();
        //var payloadSerializer = _sp.GetRequiredService<IPayloadSerializer>();
        //var apiSerializer = _sp.GetRequiredService<IApiSerializer>();
        //var safeSerializer = _sp.GetRequiredService<ISafeSerializer>();
        //var _activityVisitor = _sp.GetRequiredService<IActivityVisitor>();
        var variableManager = _sp.GetRequiredService<IWorkflowInstanceVariableManager>();

        var result = new List<WorkflowInstanceDetail>();

        var instance = instanceDao.GetInstanceById(instanceId);
        if (instance == null) { throw new Exception("未找到流程实例信息"); }

        var defVersion = definitionDao.GetDefById(instance.DefinitionId, instance.Version);


        if (defVersion == null) { throw new Exception("未找到流程定义信息"); }

        var model = activitySerializer.Deserialize(defVersion.StringData);

        var activities = ((Elsa.Workflows.Activities.Container)model).Activities;
        var activityRecords = activityRecordDao.GetActivityRecordByInstanceId(instanceId);
        var executelogRecords = executeLogRecordDao.GetExecuteRecordByInstanceId(instanceId);
        var runtimeVariables = variableManager.GetVariablesAsync(instanceId).GetAwaiter().GetResult();

        var orderedActivityRecord = activityRecords.Where(t => activities.Select(t=>t.Id).Contains(t.ActivityId)).OrderBy(t=>t.StartedAt);
        foreach (var activityRecord in orderedActivityRecord)
        {
            var activity = activities.FirstOrDefault(t => t.Id == activityRecord.ActivityId);
            
            var detail = ActivityExecuteDetailHandlerFactory.GetHandler(activity, activityRecord, runtimeVariables, instance)?.GetActivityExecuteDetail();
            if (detail != null)
            {
                result.Add(detail);
            }
            ;
            if (activityRecord.ActivityType == "Elsa.ForEach"||
                activityRecord.ActivityType == "Elsa.ParallelForEach" ||
                activityRecord.ActivityType== "Elsa.FasIterationActivity" || 
                activityRecord.ActivityType == "Elsa.FasParallelIterationActivity")
            {
                var flowChartActivities = executelogRecords.Where(t => t.ParentActivityInstanceId == activityRecord.Id).OrderBy(t => t.Sequence).Select(t => t.ActivityInstanceId).Distinct();
                var foreachChildActivies = ((Elsa.Workflows.Activities.Container)((Elsa.Workflows.Activities.ForEach<object>)activity).Body).Activities;
                foreach (var activityInstanceId in flowChartActivities)
                {
                    //parentActitity的执行信息=》对应ForEach下面的第一级flowChart
                    var parentActivityRecord = activityRecords.Find(t => activityInstanceId == t.Id);
                    //子级actitivy的执行信息=>对应包裹在ForEach里面的各种子activity
                    var childExecutelogs = executelogRecords.Where(t => activityInstanceId == t.ParentActivityInstanceId).Select(t => t.ActivityInstanceId);

                    var orderedActivityRecords = activityRecords.Where(t => childExecutelogs.Contains(t.Id)).OrderBy(t => t.StartedAt);

                    foreach (var childActivityRecord in orderedActivityRecords)
                    {
                        var childActivity = foreachChildActivies.FirstOrDefault(t => t.Id == childActivityRecord.ActivityId);
                        detail = ActivityExecuteDetailHandlerFactory.GetHandler(childActivity, childActivityRecord, runtimeVariables, instance)?.GetActivityExecuteDetail();
                        if (detail != null)
                        {
                            detail.ExecutionMetaData = new ExecutionMetaData { IterationID = activity.Id };
                            result.Add(detail);
                        }
                    }
                }
            }
        }
        return result;
    }
    /// <summary>
    /// 获取工作执行详细信息
    /// </summary>
    /// <param name="defJson"></param>
    public  List<WorkflowInstanceDetail> GetExecuteDetailNew(string instanceId,
        CancellationToken cancellationToken = default)
    {
        var instanceDao = new WorkflowInstanceDao();
        var definitionDao = new WorkflowDefinitionDao();
        var activityRecordDao = new ActivityExecutionRecordDao();
        var executeLogRecordDao = new WorkflowExecutionLogRecordDao();

        var activitySerializer = _sp.GetRequiredService<IActivitySerializer>();
        var store = _sp.GetRequiredService<IWorkflowDefinitionStore>();
        //var bookMarkSerializer = _sp.GetRequiredService<IBookmarkPayloadSerializer>();
        //var payloadSerializer = _sp.GetRequiredService<IPayloadSerializer>();
        //var apiSerializer = _sp.GetRequiredService<IApiSerializer>();
        //var safeSerializer = _sp.GetRequiredService<ISafeSerializer>();
        //var _activityVisitor = _sp.GetRequiredService<IActivityVisitor>();
        var variableManager = _sp.GetRequiredService<IWorkflowInstanceVariableManager>();

        var result = new List<WorkflowInstanceDetail>();

        var instance = instanceDao.GetInstanceById(instanceId);
        if (instance == null) { throw new Exception("未找到流程实例信息"); }

        var defVersion = definitionDao.GetDefById(instance.DefinitionId, instance.Version);
     


        if (defVersion == null) { throw new Exception("未找到流程定义信息"); }

        //var workflowDefinitions = await store.FindManyAsync(new WorkflowDefinitionFilter { DefinitionId = instance.DefinitionId }, cancellationToken);
        //var workflowDefinition = workflowDefinitions.FirstOrDefault(t => t.Version == instance.Version);
        //var workflow = await _defSrv.MaterializeWorkflowAsync(workflowDefinition, cancellationToken);

        var executelogRecords = executeLogRecordDao.GetExecuteRecordByInstanceId(instanceId);
        var runtimeVariables = variableManager.GetVariablesAsync(instanceId).GetAwaiter().GetResult();
        var activityIndex = 0;

        var model = activitySerializer.Deserialize(defVersion.StringData);

        var activities = ((Container)model).Activities;
        var connections = ((Flowchart)model).Connections;
        var activityRecords = activityRecordDao.GetActivityRecordByInstanceId(instanceId);
        Dictionary<string, ActivityNodeRuntimeInfo> dicActivityRuntimeInfo= new Dictionary<string, ActivityNodeRuntimeInfo>();

        var orderedActivityRecord = activityRecords.Where(t => activities.Select(t => t.Id).Contains(t.ActivityId)).OrderBy(t => t.StartedAt);
        foreach (var activityRecord in orderedActivityRecord)
        {
            var activity = activities.FirstOrDefault(t => t.Id == activityRecord.ActivityId);
            var detail = ActivityExecuteDetailHandlerFactory.GetHandler(activity, activityRecord, runtimeVariables, instance)?.GetActivityExecuteDetail();

            if (detail != null)
            {
                //判断此节点可以连接的节点
                var targetActivityIds = connections.Where(t => t.Source.Activity.Id == activity.Id).Select(t => t.Target.Activity.Id);
                //判断这此子节点是否都执行到了，如果只执行了一个，则平铺展示，如果是多个则生成并行节点ID
                var targetActivityExecuteList= activityRecords.Where(t => targetActivityIds.Contains(t.ActivityId));
                if (targetActivityExecuteList.Count() > 1)
                {
                    var activityParallelId = Guid.NewGuid().ToString();
                    foreach (var targetActivity in targetActivityExecuteList)
                    {
                        dicActivityRuntimeInfo[targetActivity.ActivityId] = new ActivityNodeRuntimeInfo { ActivityId = targetActivity.ActivityId, ParallelID = activityParallelId, ParallelStartNodeID = targetActivity.ActivityId, ParentActivityId = activity.Id, ParallelStartActivityInstanceDetail = detail };
                    }
                }
                else
                {
                    //获取父级节点的执行信息
                    var parentActivityRuntimeInfo = dicActivityRuntimeInfo.ContainsKey(activity.Id) ? dicActivityRuntimeInfo[activity.Id] : null;

                    foreach (var targetActivity in targetActivityExecuteList)
                    {
                        dicActivityRuntimeInfo[targetActivity.ActivityId] = new ActivityNodeRuntimeInfo { ActivityId = targetActivity.ActivityId, ParallelID = parentActivityRuntimeInfo?.ParallelID, ParallelStartNodeID = parentActivityRuntimeInfo?.ParallelStartNodeID, ParentActivityId = parentActivityRuntimeInfo?.ParentActivityId, ParallelStartActivityInstanceDetail = parentActivityRuntimeInfo?.ParallelStartActivityInstanceDetail };
                    }
                }

                if (dicActivityRuntimeInfo.ContainsKey(activity.Id))
                {
                    detail.ExecutionMetaData = new ExecutionMetaData();
                    var activityRuntimeInfo = dicActivityRuntimeInfo[activity.Id];
                    detail.ParallelID = activityRuntimeInfo.ParallelID;
                    detail.ParallelStartNodeID = activityRuntimeInfo.ParallelStartNodeID;
                   
                    detail.ExecutionMetaData.ParallelID = activityRuntimeInfo.ParallelID;
                    detail.ExecutionMetaData.ParallelStartNodeID = activityRuntimeInfo.ParallelStartNodeID;

                    if (activity.GetType() != typeof(FasEndActivity) && !string.IsNullOrEmpty(activityRuntimeInfo.ParallelStartNodeID))
                    {
                        var startActivityRuntimeInfo = dicActivityRuntimeInfo[activityRuntimeInfo.ParallelStartNodeID];
                        if (startActivityRuntimeInfo != null && detail.ActivityId != startActivityRuntimeInfo.ParallelStartNodeID)
                        {
                            detail.ParentParallelID = startActivityRuntimeInfo.ParallelID;
                            detail.ParentParallelStartNodeID = startActivityRuntimeInfo.ParallelStartNodeID;
                            detail.ExecutionMetaData.ParentParallelID = startActivityRuntimeInfo.ParallelID;
                            detail.ExecutionMetaData.ParentParallelStartNodeID = startActivityRuntimeInfo.ParallelStartNodeID;
                        }
                    }
                }
                detail.Index = activityIndex++;
                result.Add(detail);
            }
            ;
            if (activityRecord.ActivityType == "Elsa.ForEach" ||
                activityRecord.ActivityType == "Elsa.ParallelForEach" ||
                activityRecord.ActivityType == "Elsa.FasIterationActivity" ||
                activityRecord.ActivityType == "Elsa.FasParallelIterationActivity")
            {
                var flowChartActivities = executelogRecords.Where(t => t.ParentActivityInstanceId == activityRecord.Id).OrderBy(t => t.Sequence).Select(t => t.ActivityInstanceId).Distinct();
                var foreachChildActivies = ((Elsa.Workflows.Activities.Container)((Elsa.Workflows.Activities.ForEach<object>)activity).Body).Activities;
                var iterationIndex = 0;
                foreach (var activityInstanceId in flowChartActivities)
                {
                    //parentActitity的执行信息=》对应ForEach下面的第一级flowChart
                    var parentActivityRecord = activityRecords.Find(t => activityInstanceId == t.Id);
                    //子级actitivy的执行信息=>对应包裹在ForEach里面的各种子activity
                    var childExecutelogs = executelogRecords.Where(t => activityInstanceId == t.ParentActivityInstanceId).Select(t => t.ActivityInstanceId);
                    
                    var orderedActivityRecords = activityRecords.Where(t => childExecutelogs.Contains(t.Id)).OrderBy(t => t.StartedAt);
                    
                    foreach (var childActivityRecord in orderedActivityRecords)
                    {
                        var childActivity = foreachChildActivies.FirstOrDefault(t => t.Id == childActivityRecord.ActivityId);
                        detail = ActivityExecuteDetailHandlerFactory.GetHandler(childActivity, childActivityRecord, runtimeVariables, instance)?.GetActivityExecuteDetail();
                        if (detail != null)
                        {
                            detail.ExecutionMetaData = new ExecutionMetaData { IterationID = activity.Id,IterationIndex= iterationIndex};
                            result.Add(detail);
                        }
                    }
                    iterationIndex++;
                }
            }
        }
        return result;
    }
    
    //private void GetDetail(ActivityExecutionRecord record, ICollection<IActivity> activities, T.FAS.Runtime.MF.Entity.ElsaEntity.WorkflowInstance instance)
    //{
    //    var stateSerializer = _sp.GetRequiredService<IWorkflowStateSerializer>();

    //    if (!string.IsNullOrEmpty(record.SerializedActivityState))
    //    {
    //        var stateInfo = stateSerializer.Deserialize(record.SerializedActivityState);
    //    }
    //    var inputs = new Dictionary<string, object>();

    //    var runtimeVariables = variableManager.GetVariablesAsync(record.WorkflowInstanceId).GetAwaiter().GetResult();
    //    if (record.ActivityName == "Elsa.FasStartActivity")
    //    {
    //        var actitivity = activities.FirstOrDefault(t => t.Id == record.ActivityId);
    //        var startActivity = actitivity as FasStartActivity;

    //        if (startActivity.Inputs != null && startActivity.Inputs.Count() > 0)
    //        {
    //            foreach (var item in startActivity.Inputs)
    //            {
    //                inputs.Add(item.Label, runtimeVariables.FirstOrDefault(t => t.Variable.Name == item.Label)?.Value);
    //            }
    //        }
    //    }
    //}

    #region 私有方法


    private static async Task<ElsaEngine> CreateEngineInstance()
    {
        string pgConnectionString = GetElsaPGConnStrFromConfigCenter();

        // 1) 构建服务容器
        var services = new ServiceCollection();
       services.AddSingleton<IConfiguration>(new ConfigurationBuilder().Build());

        //FAS表达式引擎服务

        services.AddTransient<FasExpService>();
        services.AddTransient<FasExpDebugService>();
        services.AddTransient<FasExpSdkService>();
        services.AddTransient<Func<string, IFasExpService>>(serviceProvider => mode =>
        {
            return mode switch
            {
                "publish" => serviceProvider.GetRequiredService<FasExpSdkService>(),
                "debug" => serviceProvider.GetRequiredService<FasExpDebugService>()
            };
        });

       
        //大模型服务
        services.AddTransient<QwenMaxRequestService>();
        services.AddTransient<Func<string, ILLMModelRequestService>>(serviceProvider => modelName =>
        {
            return modelName switch
            {
                "qwen-max" => serviceProvider.GetRequiredService<QwenMaxRequestService>(),
                "qwenMax0125" => serviceProvider.GetRequiredService<QwenMaxRequestService>(),
                "qwenMaxlatest" => serviceProvider.GetRequiredService<QwenMaxRequestService>(),
                "qwq:32b" => serviceProvider.GetRequiredService<QwenMaxRequestService>(),
                _ => throw new ArgumentException($"No processor registered for model: {modelName}")
            };
        });

        // 2) 注册 Elsa：同时配置“管理端”（读定义）和“运行时”
        services.AddElsa(elsa => elsa
        .AddActivitiesFrom<ConditionBranchActivity>()
               .AddActivitiesFrom<CDOActivity>()
               .AddActivitiesFrom<FasStartActivity>()
               .AddActivitiesFrom<FasEndActivity>()
            .UseWorkflowManagement(mgmt => mgmt
                .UseEntityFrameworkCore(ef => ef.UsePostgreSql(pgConnectionString)))
            .UseWorkflowRuntime(rt => rt
                .UseEntityFrameworkCore(ef => ef.UsePostgreSql(pgConnectionString)))
            .UseJavaScript()
            .UseCSharp()
            .UseHttp()
            .AddActivitiesFrom<ElsaEngine>()
            .AddWorkflowsFrom<ElsaEngine>());

        // 3) 构建 ServiceProvider
        var serviceProvider = services.BuildServiceProvider();

        // 4) !!! 关键步骤：手动执行 Elsa 的启动服务 !!!
        // 获取所有 IHostedService 实例
        await InitializeHostedServices(serviceProvider);

        //5) 创建 ElsaEngine 实例并返回
        return new ElsaEngine(serviceProvider);
    }

    private static async Task InitializeHostedServices(IServiceProvider serviceProvider)
    {
        var hostedServices = serviceProvider.GetServices<IHostedService>();
        foreach (var hostedService in hostedServices)
        {
            // 启动服务，这将触发 ActivityRegistry 的填充
            await hostedService.StartAsync(CancellationToken.None);
        }
    }
    /// <summary>
    /// 获取流程定义
    /// </summary>
    /// <param name="definitionHandle"></param>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    /// <exception cref="InvalidOperationException"></exception>
    private async Task<WorkflowDefinition> GetWorkflowAsync(string defId, CancellationToken cancellationToken)
    {
        var store = _sp.GetRequiredService<IWorkflowDefinitionStore>();
        return await store.FindLastVersionAsync(new WorkflowDefinitionFilter { DefinitionId = defId }, cancellationToken);
    }


    private static string GetElsaPGConnStrFromConfigCenter()
    {
        var mfDbConnectionString = "server=127.0.0.1;database=tmf;user id=root;password=EKV5tMYyZjrcFhOzEQ8z;provider=PostgreSql4.0.13;name=PostgreSql;port=5432;";
        
        //从配置中心获取连接字符串
        var dbConfigKey = "TTP.Database.TMF.ConnectionString";
        var configurationService = new T.FAS.Runtime.MF.Runtime.Core.ConfigCenterService();
        mfDbConnectionString = configurationService.GetConfigValueFromConfigCenter(dbConfigKey);

        var mfPgConnectionString = ConnectionStringConverter.Convert(mfDbConnectionString);

        return mfPgConnectionString;
        // return "Server=127.0.0.1;Username=root;Database=tmf;Port=5432;Password=EKV5tMYyZjrcFhOzEQ8z;MaxPoolSize=2000;Timeout=60";

        //return "Server=127.0.0.1;Username=root;Database=tmf;Port=5432;Password=EKV5tMYyZjrcFhOzEQ8z;MaxPoolSize=2000;Timeout=60";
    }
    #endregion

    public void Dispose()
    {
        _sp?.Dispose();
        // 重置单例实例（如果需要重新初始化）
        if (_lazyInstance.IsValueCreated)
        {
            var _ = _lazyInstance.Value.ContinueWith(t =>
            {
                if (t.IsCompletedSuccessfully) t.Result.Dispose();
            });
        }
    }
}